package com.hhxy.web;

import com.hhxy.pojo.User;
import com.hhxy.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    UserService service = new UserService();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1、获取Service对象
        //2、获取用户输入参数
//        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");



        //获取复选框数据，实现记住我的功能
        String remember = request.getParameter("remember");
        if("1".equals(remember)){//这里是个小细节，阿里巴巴规范，常量调用equals方法避免空指针异常
            //勾选了复选框，就向浏览器发送Cookie（复选框没设置值，默认是on）
            Cookie c_username = new Cookie("username",username);
            Cookie c_password = new Cookie("password",password);
            c_username.setMaxAge(60*60*24*7);//Cookie在浏览器上保存七天
            c_password.setMaxAge(60*60*24*7);
            response.addCookie(c_username);
            response.addCookie(c_password);
        }

        //3、调用Service对象的方法完成，看数据库中是否存在该用户
        User user = service.login(username, password);
        //4、判断登录是否成功
        if (user != null) {
            //登录成功，跳转到SelectAllServlet
            //将uer对象存储到到Session对象中，实现登录界面动态获取用户名
            HttpSession session = request.getSession();
            session.setAttribute("user",user);
            // String contextPath = request.getContextPath();//动态获取虚拟目录，可要可不要。写一下主要是增加记忆
            response.sendRedirect("/day12_LoginAndRegister/SelectAllServlet");//重定向实现跳转
        }else{
            //登录失败，跳转到login.jsp页面中，同时要携带参数
            System.out.println("登录失败！");
            request.setAttribute("login_msg","用户名或密码错误");
            //实现数据共享，使用请求转发
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
        }
    }
}
